/**
 * 报价添加
 */
define(function (require, exports, module) {

    require("JTemplate");
    require("ajaxproxy");
    require("layer");

    var common = require('common');

    var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';

    exports.init = function (rowIndex, product_name, factory_name, brand_name, tpfb, type_name) {

        //添加数据
        $('[data-act=do_add]').on("click", function () {

            if ($(this).hasClass("grayBtn")) {
                return;
            }
            if (!doSumbit()) {
                return false;
            }

            $.post($("#addOfferFrom").attr('action'), $("#addOfferFrom").serialize(), function (result) {
                var ajax = $.parseJSON(result);
                if (ajax.code == "000") {
                    layer.msg('提交成功', {shift: -1}, function () {

                        window.location.href = '/mobadmin/offer/detail?offer_id=' + ajax.data.offer_id + "&shareSuccessPanel=1";
                    });
                } else {
                    layer.msg("提交失败");
                }
            });
        });
        //从自定义牌号页面跳转，回的当初跳过去的行数
        if (rowIndex) {
            if (window.localStorage) {
                var tableHtml = localStorage.getItem("tableHtml");
                var tableInpStr = localStorage.getItem("tableInpStr");
                tableInpVals = tableInpStr.split(",");
                if (tableHtml && tableHtml != "") {
                    $(".bjtable").html(tableHtml);
                    $(".addBjInp").each(function (i) {
                        $(this).val(tableInpVals[i]);
                    });
                    $(".bjtable li .pinmingCol").click(function () {
                        showBJ.apply(this);
                    });
                    var Col = $(".bjtable li[data-id=" + rowIndex + "] .pinmingCol");
                    Col.addClass("pinmingColSel");
                    Col.attr("data-tpfb", tpfb);
                    Col.find(".txt_pro").html(product_name);
                    Col.find(".txt_fac").html(factory_name);
                    Col.find(".txt_bra").html(brand_name);
                    Col.attr("data-type", type_name);
                    data_id = $(".bjtable tr:last").attr("data-id");
                }

            }
        }
        //修改按钮触发
        $('.modifyBtn').click(function () {


            touchMove();
            //弹出牌号
            $(".bjtable li .pinmingCol").click(function () {

                showBJ.apply(this);

            });

            $(".addrowBtn").show();
            $(".addBjInp").removeAttr('readonly');
            $(".modifyInp").removeAttr('readonly');
            $(".modifyBtn").hide();
            $(".saveBtn").show();

            if ($("#phoneInp2").val() != "") {
                $("#addPhoneBtn").hide();
                $("#delPhoneBtn").show();
                $("#delPhoneBtn2").show();

            } else {
                $("#addPhoneBtn").show();
                $("#delPhoneBtn").hide();
            }

        });

    };


    function doSumbit() {

        var offerProducts = [];//报价产品信息
        var bool = true;
        $(".bjtable li.tb_row").each(function () {

            var select_tr_obj = $(this);

            var select_input_obj = select_tr_obj.find('.pinmingCol');

            var type_name = select_input_obj.attr('data-type')

            var product_name = select_input_obj.find('.txt_pro').html();
            var factory_name = select_input_obj.find('.txt_fac').html();
            var brand_name = select_input_obj.find('.txt_bra').html();
            var tpfb = select_input_obj.attr('data-tpfb');
            var quantity = select_tr_obj.find('[data-act=quantity]').val();
            var sales_price = select_tr_obj.find('[data-act=sales_price]').val();

            var product = '{"type_name":"' + type_name + '","product_name":"' + product_name + '","factory_name":"' + factory_name + '","brand_name":"' + brand_name + '","tpfb":"' + tpfb + '","quantity":"' + quantity + '","sales_price":"' + sales_price + '"}';

            //如果此行有为空项
            if (tpfb == '' || type_name == '' || product_name == '' || factory_name == '' || brand_name == '' || quantity == '' || sales_price == '') {
                //如果此行不全为空，则跳过，返回
                if (tpfb == '' && quantity == '' && sales_price == '' && offerProducts.length >= 1) {
                    return true;
                }
                bool = false;
                return false;
            } else {

                offerProducts.push(product);
            }
        });

        var ss = '[' + offerProducts.join(',') + ']';

        $('input[name="data[offer_products]"]').val(ss);

        if ($('input[name="data[contact_mobile]"]').val() == '' || $('input[name="data[contact]"]').val() == '') {
            layer.msg('请输入联系方式和公司名');

            return false;
        }

        var mobile = $('input[name="data[contact_mobile]"]').val();
        var mobile2 = $('input[name="data[contact_mobile2]"]').val();

        if (!(checkPhone(mobile) || checkTel(mobile))) {
            layer.msg('联系方式格式不正确');
            return false;
        }

        if (mobile2 != '' && !(checkPhone(mobile2) || checkTel(mobile2))) {
            layer.msg('联系方式格式不正确');
            return false;
        }

        if (!bool) {
            layer.msg('请输入完整信息');
        }

        return bool;
    }

    //滑动删除
    function touchMove() {
        //划动报价的li行，显示“取消”，“删除”
        var silde_row = $('.bjtable li.tb_row');
        var w = silde_row.find('.btn').width();
        var touchTargen, startX;
        for (var i = 0; i < silde_row.length; i++) {
            silde_row[i].addEventListener('touchstart', function (e) {
                var touch = e.touches[0];

                startX = touch.pageX;

                touchTargen = $(this);
            });
            silde_row[i].addEventListener('touchend', function (e) {
                touchTargen = undefined;
            });
        }
        window.addEventListener('touchmove', function (e) {
            var touch = e.touches[0];

            var deltaX = touch.pageX - startX;
            if (deltaX < 0) {
                //向左滑动，显示btn
                touchTargen && touchTargen.stop(true).animate({left: -w + 'px'}).siblings(".tb_row").animate({left: 0});
            } else {
                touchTargen && touchTargen.stop(true).animate({left: 0});
            }
        });
        //点击“取消”，“删除”
        silde_row.on('click', 'span.cancel', function () {
            $(this).closest('.tb_row').animate({left: 0});
        }).on('click', 'span.delete', function () {
            $(this).closest('.tb_row').remove();
        });
    }

    //关闭报价弹窗
    function panelClose() {
        $(".tpfb_panel").addClass("slideOutRight").one(animationEnd, function () {
            $(this).removeClass('braPanelBounceIn slideOutRight');
        });
    }

    //点击牌号文本框，弹出牌号选择框
    function showBJ() {

        var select_data_id = $(this).parents('li').attr('data-id');

        $(this).parents('.addBJ').find('.tpfb_panel').attr('data-id', select_data_id);
        $(this).parents('.addBJ').find('.tpfb_panel').show();
        var brandName = $(this).find('.txt_bra').html();
        if (brandName == '牌号') {
            brandName = '77';
            setBrandSearchData(brandName, '');
        } else {
            setBrandSearchData(brandName, 'GP');
        }
        $(".customLink").attr("href","/mobadmin/brand/add?offerFrom=detail&offerFromId=" + offer_id+"&dataId=" + select_data_id);

        if (window.localStorage) {
            localStorage.setItem("tableHtml", $(".bjtable").html());
            var addBjInpStr = "";
            $(".addBjInp").each(function () {
                addBjInpStr += $(this).val() + ",";
            });
            addBjInpStr = addBjInpStr.substring(0, addBjInpStr.length - 1);
            localStorage.setItem("tableInpStr", addBjInpStr);
        }


        $(".braPanel").addClass("slideInRight").one(animationEnd, function () {
            $(this).addClass("braPanelBounceIn").removeClass('slideInRight');
        });

    }

    //牌号文本框,选中某牌号
    function selectRowFun() {
        if ($(this).attr("name")) {
            $(".selectRow[name=" + $(this).attr("name") + "]").removeClass("selectOn").find(".selectInpEl").val("off");
        }

        $(this).addClass("selectOn");
        $(this).find(".selectInpEl").val("on");

        selectAction.apply(this);
    }

    //设置牌号搜索内容
    function setBrandSearchData(brandName, brandName2) {

        getBrandList(brandName, brandName2, function (data) {

            var s = "";
            var s_p = "";//公告牌号内容
            var s_c = "";//自定义牌号内容

            $(data.public).each(function (index, el) {

                var selectInpEl_value = 'off';
                var selectRow_class = '';

                s_p = s_p + '<div class="zimuRow">' + el.lt + '</div>';

                $(el.lt_items).each(function (index2, el2) {


                    s_p = s_p + '<div class="selectRow ' + selectRow_class + '"  value="' + el2.id + '" name="bra">' +
                        '<span style="display: none" class="txt_typ" data-id="' + el2.typeid + '">' + el2.typename + '</span>' +
                        '<div class="selectTxtWrap"><span class="selectTxt txt_pro" data-id="' + el2.brandid + '">' + el2.brand + '</span>/' +
                        '<span class="selectTxt txt_fac" data-id="' + el2.facid + '">' + el2.factory + '</span>/' +
                        '<span class="selectTxt txt_bra" data-id="' + el2.id + '">' + el2.name + '</span></div>' +
                        '<span class="radioBtn"><span class="radioCore"></span></span>' +
                        '<input type="hidden" class="selectInpEl" value="' + selectInpEl_value + '"/>' +
                        '</div>';
                });

            });

            $(data.custom).each(function (index, el) {

                var selectInpEl_value = 'off';
                var selectRow_class = '';

                if (index == 0) {
                    selectInpEl_value = 'on';
                    selectRow_class = 'selectOn';
                } else {
                    selectInpEl_value = 'off';
                    selectRow_class = '';

                }
                s_c = s_c + '<div class="selectRow ' + selectRow_class + '"  value="' + el.id + '" name="bra">' +
                    '<span style="display: none" class="txt_typ" data-id="' + el.typeid + '">' + el.typename + '</span>' +
                    '<div class="selectTxtWrap"><span class="selectTxt txt_pro" data-id="' + el.brandid + '">' + el.brand + '</span>/' +
                    '<span class="selectTxt txt_fac" data-id="' + el.facid + '">' + el.factory + '</span>/' +
                    '<span class="selectTxt txt_bra" data-id="' + el.id + '">' + el.name + '</span></div>' +
                    '<span class="radioBtn"><span class="radioCore"></span></span>' +
                    '<input type="hidden" class="selectInpEl" value="' + selectInpEl_value + '"/>' +
                    '</div>';


            });
            if (s_c != '') {

                s_c = '<div class="zimuRow">自定义牌号库</div>' + s_c;

            }

            s = s_c + s_p;
            $('.braContent').html(s);
            $('.braContent').find(".selectRow").click(function () {
                selectRowFun.apply(this);
            });
        });

    }


    //牌号选择框，确定按钮
    function selectAction() {
        panelClose();
        var typ_obj = $(this).parents('.tpfb_panel').find('.selectOn').find('.txt_typ');
        var pro_obj = $(this).parents('.tpfb_panel').find('.selectOn').find('.txt_pro');
        var fac_obj = $(this).parents('.tpfb_panel').find('.selectOn').find('.txt_fac');
        var bra_obj = $(this).parents('.tpfb_panel').find('.selectOn').find('.txt_bra');

        var select_data_id = $(this).parents('.tpfb_panel').attr('data-id');

        var select_tr_obj = $('li[data-id=' + select_data_id + ']');

        var select_input_obj = select_tr_obj.find('.pinmingCol');
        select_input_obj.addClass("pinmingColSel");
        var s = pro_obj.html();
        //s=s.substring(0,s.length-1);
        select_input_obj.find('.txt_pro').html(s);
        s = fac_obj.html();//s=s.substring(0,s.length-1);
        select_input_obj.find('.txt_fac').html(s);
        s = bra_obj.html();//s=s.substring(0,s.length-1);
        select_input_obj.find('.txt_bra').html(s);

        var tpfb = typ_obj.attr('data-id') + '-' + pro_obj.attr('data-id') + '-' + fac_obj.attr('data-id') + '-' + bra_obj.attr('data-id');

        select_input_obj.attr('data-tpfb', tpfb);
        select_input_obj.attr('data-type', typ_obj.html());

    }

    //获取牌号数据
    function getBrandList(brandName, brandName2, callback) {
        brandName = encodeURI(brandName);
        var url = "/mobadmin/brand/searchBrand?timestamp=" + new Date().getTime() + "&brand_name=" + brandName + "&brand_name2=" + brandName2;
        $.getJSON(url, function (data) {
            callback(data);
        });
    }




    //牌号文本框,搜索按钮
    $(document).on('click', ".searchBtn", function () {

        var brandName = $('.serchInp').val();

        setBrandSearchData(brandName, '');
    });

    $(document).on('input', ".serchInp", function () {

        var brandName = $('.serchInp').val();
        setBrandSearchData(brandName, '');
    });


    //新增报价
    var data_id =  $(".bjtable li:last").data('id');

    $("[data-act=add_product]").click(function () {
        data_id++;
        var data = '{"data_id":"' + data_id + '"}';

        var temp = JTemplate.render("lookTemp", jQuery.parseJSON(data));

        $(".bjtable li:last").after(temp);

        $(".bjtable li:last .pinmingCol").click(function () {
            showBJ.apply(this);
        });

        touchMove();
    });


    $(".searchPop").click(function () {
        $(".searchBtn").show();
        $(".searchPop").hide();
        $(".serchInp").focus();
    });

    $(".serchInp").blur(function () {
        if ($.trim($(".serchInp").val()) == "") {
            $(".searchBtn").hide();
            $(".searchPop").show();
        }
    });


    //关闭报价弹窗
    $(".panelClose,.cd_cancel,.masker").click(function () {

        panelClose();
    });


    window.setInterval(function () {
        var contactVal = $.trim($("#contactInp").val());
        var phoneVal = $.trim($("#phoneInp1").val());
        if (phoneVal == "" || contactVal == "") {
            $("[data-act='do_add']").addClass("grayBtn");
        } else {
            $("[data-act='do_add']").removeClass("grayBtn");
        }
    }, 500);

});
